<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminAdmin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class AdminController extends Controller
{
    /**
     * 登录
     * @param Request $request
     * @return false|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
     */
    public function login(Request $request)
    {
        if ($request->ajax()) {
            $rule    = [
                'username' => 'required',
                'password' => 'required',
            ];
            $message = [
                'username.required' => '账号不能为空',
                'password.required' => '密码不能为空',
            ];
            $res     = Validator::make($request->all(), $rule, $message);
            if ($res->fails()) {
                return self::failed($res->errors()->first());
            }
            if (strtolower($request->input('vcode', 'default')) != strtolower(session('code'))) {
                $request->session()->forget('code');
                return self::failed('图像验证码错误');
            }
            $res = AdminAdmin::login($request->input('username'), $request->input('password'), $request->ip());
            if ($res === false) {
                return self::failed('登陆失败');
            }
            return self::ok('操作成功', route('admin.AdminController.index'));
        }
        return view('Admin.AdminLogin');
    }

    /**
     * 主页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        return view('Admin.AdminIndex');
    }

    /**
     * 退出
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function out(Request $request)
    {
        $request->session()->flush();
        return redirect()->route('admin.AdminController.login');
    }


    /**
     * 修改密码
     * @param Request $request
     * @return false|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
     */
    public function modify(Request $request)
    {
        if ($request->ajax()) {
            $bool = AdminAdmin::edit($request->input('username'), $request->input('password',false));
            if ($bool) {
                return self::ok();
            }
            return self::failed();
        }
        $admin = AdminAdmin::find(1);
        return view('Admin.AdminModify', [
            'admin' => $admin
        ]);
    }


}
